package com.bootdo.system.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.bootdo.common.controller.BaseController;
import com.bootdo.common.domain.SysDictDO;
import com.bootdo.common.service.SysDictService;
import com.bootdo.common.utils.PageUtils;
import com.bootdo.common.utils.Query;
import com.bootdo.common.utils.R;
import com.bootdo.system.domain.Order;
import com.bootdo.system.domain.Parents;
import com.bootdo.system.domain.RedBag;
import com.bootdo.system.domain.RedBagConfig;
import com.bootdo.system.service.OrderService;
import com.bootdo.system.service.ParentsService;
import com.bootdo.system.service.RedBagConfigService;
import com.bootdo.system.service.RedBagService;
import com.github.pagehelper.PageInfo;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

@RequestMapping("/sys/redBag")
@Controller
@Api(value = "/sys/redBag", description = "红包操作接口")
public class RedBagController extends BaseController {
	String prefix = "sys/redBag";
	@Autowired
	RedBagService service;

	@Autowired
	SysDictService sysDictService;
	
	@Autowired
	ParentsService parentsService;
	
	@Autowired
	OrderService orderService;

	@Autowired
	RedBagConfigService redBagConfigService;

	@ApiOperation(value="红包查询", notes="根据条件查询红包", response=String.class)
	@ApiImplicitParams({
        @ApiImplicitParam(name = "id", value = "红包id", required = false, paramType="query", dataType = "Long"),
        @ApiImplicitParam(name = "bagName", value = "红包名称", required = false, paramType="query", dataType = "String"),
        @ApiImplicitParam(name = "bagStatus", value = "红包状态", required = false,  paramType="query",dataType = "Long"),
        @ApiImplicitParam(name = "bagType", value = "红包类型", required = false,  paramType="query",dataType = "Long"),
        @ApiImplicitParam(name = "ownerId", value = "所属用户id", required = true, paramType="query", dataType = "Long"),
        @ApiImplicitParam(name = "coursePoint", value = "课程遛点", required = false,  paramType="query",dataType = "Long"),
        @ApiImplicitParam(name = "pageNum", value = "当前第几页", required = true,paramType="query", dataType = "int"),
        @ApiImplicitParam(name = "pageSize", value = "每页显示多少条", required = true,paramType="query", dataType = "int")
	})
	@GetMapping("/list")
	@ResponseBody
	R list(@RequestParam Map<String,Object> param)  throws Exception{
		
		RedBagConfig rbc = redBagConfigService.getConfig();
		if(rbc == null) {
			return R.error(1, "没有红包配置数据，无法查询可用红包");
		}
		SysDictDO dict = sysDictService.getSingleDictByType("liudian");
		if(dict == null) {
			return R.error(1, "没有配置遛点与人民币换算关系，无法查询可用红包");
		}
		List<RedBag> redBagList = null;
		if(param.get("coursePoint") != null && !"null".equals(param.get("coursePoint")+"")) {
			Long coursePoint = Long.parseLong(param.get("coursePoint")+"");
			param.put("newPoint", coursePoint*(Long.parseLong(dict.getValue()))*rbc.getMaxPercent()/100);
			param.put("sharePoint", coursePoint*rbc.getShareMaxPercent()/100);
			Query query = new Query(param);
			redBagList = service.list(query);
		}else {
			Query query = new Query(param);
			redBagList = service.myBagList(query);
		}
		PageInfo<RedBag> pageInfo = new PageInfo<RedBag>(redBagList);
		int total = (int)pageInfo.getTotal();
		PageUtils pageUtil = new PageUtils(redBagList, total);
		return new R("list",pageUtil);
	}
	
	
	
	@ApiOperation(value="最大可用红包查询", notes="根据条件查询最大可用红包", response=String.class)
	@ApiImplicitParams({
        @ApiImplicitParam(name = "orderId", value = "红包状态", required = true,  paramType="query",dataType = "Long"),
        @ApiImplicitParam(name = "ownerId", value = "所属用户id", required = true, paramType="query", dataType = "Long"),
	})
	@GetMapping("/getMaxRedBag")
	@ResponseBody
	R getMaxRedBag(Long orderId, Long ownerId)  throws Exception{
	
		if(orderId== null) {
			return R.error(1, "订单不存在");
		}
		Order order = orderService.get(orderId);
		if(order == null) {
			return R.error(1, "订单不存在");
		}
		Long coursePoint = order.getCoursePoints();
		RedBagConfig rbc = redBagConfigService.getConfig();
		if(rbc == null) {
			return R.error(1, "没有红包配置数据，无法查询可用红包");
		}
		SysDictDO dict = sysDictService.getSingleDictByType("liudian");
		if(dict == null) {
			return R.error(1, "没有配置遛点与人民币换算关系，无法查询可用红包");
		}
		Map<String,Object> param = new HashMap<String,Object>();
		param.put("orderId", orderId);
		param.put("ownerId", ownerId);
		param.put("newPoint", coursePoint*(Long.parseLong(dict.getValue()))*rbc.getMaxPercent()/100);
		param.put("sharePoint", coursePoint*(Long.parseLong(dict.getValue()))*rbc.getShareMaxPercent()/100);
		RedBag redb = service.getMaxRedBag(param);
		if(redb != null) {
			return new R("obj",service.getMaxRedBag(param));
		}else {
			return R.error(1, "无可用红包");
		}
	}
	
	@ApiOperation(value="红包详情", notes="根据条件查询红包", response=String.class)
	@ApiImplicitParams({
        @ApiImplicitParam(name = "id", value = "红包id", required = true,paramType="query",  dataType = "Long"),
	})
	@GetMapping("/edit")
	@ResponseBody
	R edit(Long id)  throws Exception{
		return new R("obj",service.get(id));
	}
	
	@ApiOperation(value="获取可用红包数量", notes="根据条件查询红包", response=String.class)
	@ApiImplicitParams({
        @ApiImplicitParam(name = "ownerId", value = "用户id", required = true,paramType="query",  dataType = "Long"),
        @ApiImplicitParam(name = "coursePoint", value = "课程遛点", required = false,  paramType="query",dataType = "Long"),
        @ApiImplicitParam(name = "bagStatus", value = "红包状态", required = false,  paramType="query",dataType = "Long"),
	})
	@GetMapping("/getTotal")
	@ResponseBody
	R getTotal(Long ownerId, Long coursePoint, Long bagStatus)  throws Exception{
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("ownerId", ownerId);
		map.put("bagStatus", bagStatus);
		if(coursePoint == null) {
			return new R("total",service.count(map));
		}else {
			RedBagConfig rbc = redBagConfigService.getConfig();
			if(rbc == null) {
				return R.error(1, "没有红包配置数据，无法查询可用红包");
			}
			SysDictDO dict = sysDictService.getSingleDictByType("liudian");
			if(dict == null) {
				return R.error(1, "没有配置遛点与人民币换算关系，无法查询可用红包");
			}
			map.put("newPoint", coursePoint*(Long.parseLong(dict.getValue()))*rbc.getMaxPercent()/100);
			map.put("sharePoint", coursePoint*rbc.getShareMaxPercent()/100);
			return new R("total",service.countCanUse(map));
		}
	}
	
	@ApiOperation(value="红包保存", notes="保存红包", response=String.class)
	@PostMapping("/save")
	@ResponseBody
	R save(@RequestBody RedBag obj)  throws Exception{
		if(obj != null) {
			obj.setCreateTime(new Date());
			obj.setBagStatus(1);
		}
		if (service.save(obj) > 0) {
			return R.saveOk(obj.getId().toString());
		} else {
			return R.error(1, "保存失败");
		}
	}

	@ApiOperation(value="红包更新", notes="更新红包", response=String.class)
	@PostMapping("/update")
	@ResponseBody
	R update(@RequestBody RedBag obj)  throws Exception{
		if (service.update(obj) > 0) {
			return R.ok();
		} else {
			return R.error(1, "更新失败");
		}
	}

	@ApiOperation(value="红包删除", notes="根据红包id删除", response=String.class)
	@ApiImplicitParams({
        @ApiImplicitParam(name = "id", value = "红包id", required = true, paramType="query", dataType = "Long"),
	})
	@PostMapping("/remove")
	@ResponseBody
	R remove(Long id)  throws Exception{
		if (service.remove(id) > 0) {
			return R.ok();
		} else {
			return R.error(1, "删除失败");
		}
	}
	
	
	@ApiOperation(value="发送新人红包", notes="", response=String.class)
	@ApiImplicitParams({
        @ApiImplicitParam(name = "userId", value = "前台用户id", required = true,paramType="query",  dataType = "Long"),
	})
	@GetMapping("/saveNewRedBag")
	@ResponseBody
	R saveNewRedBag(Long userId)  throws Exception{
		
		Parents p = parentsService.get(userId);
		if(p == null) {
			return R.error("用户不存在");
		}
		Map<String,Object> sysParam = new HashMap<String,Object>();
		sysParam.put("type", "newUserRedBag");
		List<SysDictDO> dictList = sysDictService.list(sysParam);
		RedBag rb = new RedBag();
		if(dictList != null && dictList.size()>0) {
			rb.setBagMoney(Double.parseDouble(dictList.get(0).getValue()));
		}
		rb.setBagName("新用户红包");
		rb.setBagStatus(0);
		rb.setOwnerId(userId);
		service.save(rb);
		return new R("id",rb.getId());
	}

}
